import Troop, Mission, Base, Defines, pygame, random, Sound , Basecom
from pygame.locals import *

#             R    G    B
WHITE     = (255, 255, 255)
BLACK     = (  0,   0,   0)
RED       = (255,   0,   0)
GREEN     = (  0, 255,   0)
DARKGREEN = (  0, 155,   0)
DARKGRAY  = ( 40,  40,  40)
BGCOLOR = BLACK

class Game:
    def __init__(self):
    	pygame.init()
    	self.FPSCLOCK = pygame.time.Clock()
    	self.DISPLAYSURF = pygame.display.set_mode((Defines.WINDOWWIDTH, Defines.WINDOWHEIGHT))
    	self.BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
    	pygame.display.set_caption('BaseCom')

    	# name, troopType, level
    	self.troop1 = Troop.Troop("troop1", "soldier", 1)
    	self.troop2 = Troop.Troop("troop2", "sniper", 1)
    	self.troop3 = Troop.Troop("troop3", "heavy", 1)
    	self.troop4 = Troop.Troop("troop4", "scout", 1)

    	# list of troops
    	self.troopList = [self.troop1, self.troop2, self.troop3, self.troop4]
    	self.troopList = list(self.troopList)


        self.state = Defines.State.MAIN
        #make base
        self.base = Base.Base()

        #init sounds
        self.sound = Sound.Sound()

        self.emptyRoomImage = pygame.image.load('Images/Empty.jpg')
        self.shaftRoomImage = pygame.image.load('Images/Shaft.jpg')
        self.moneyRoomImage = pygame.image.load('Images/Money.jpg')
        self.med_bayRoomImage = pygame.image.load('Images/Med_bay.jpg')
        self.barracksRoomImage = pygame.image.load('Images/Barracks.jpg')
        self.powerRoomImage = pygame.image.load('Images/Power.jpg')

    def generateReward(self):
    	reward = random.randint(Defines.RewardType.NONE, Defines.RewardType.WEAPON)
    	#if reward == RewardType.NONE:
    		#no reward
    	if reward == Defines.RewardType.money:
    		self.money += self.mission1.money * 2
    	elif reward == Defines.RewardType.XP:
    		self.mission1.xp += self.mission1.xp * 2
    	elif reward == Defines.RewardType.SCIENCE:
    		self.science += random.randint(50, 150) * self.mission1.difficulty
    	#elif reward == RewardType.ARMOUR:
    		#give armour
    	#elif reward == RewardType.WEAPON:
    		#give weapon

    def game_update(self ):
		#print 'We are the {} who say "{}!"'.format('knights', 'Ni')
		if self.state == Defines.State.MAIN:
			for event in pygame.event.get(): # event handling loop
				if event.type == QUIT:
					Basecom.terminate()
				elif event.type == KEYDOWN:
					if (event.key == K_b):
						state = Defines.State.ROOMSELECT
					elif (event.key == K_SPACE):
						state = Defines.State.MISSIONSELECT

		if self.state == Defines.State.ROOMSELECT:
			if self.base.selectRoom():
				self.state = Defines.State.BUILDINGSELECT
		if self.state == Defines.State.BUILDINGSELECT:
			if self.base.changeRoom():
				self.state = Defines.State.MAIN
		if self.state == Defines.State.MISSIONSELECT:
			self.mission1 = Mission.Mission()
			if self.mission1.difficulty_choice():
				self.state = Defines.State.CHARSELECT

		if self.state == Defines.State.CHARSELECT:
			self.troopList = self.mission1.attempt(self.troopList)
			if self.mission1.health <= 0:
				#gain reward
				self.generateReward()
				for i in range (len(self.troopList)):
					if self.troopList[i].injured == True:
						if random.randint(0, 100) < 75: #minus number of med_bays * 5
							self.troopList[i] = Troop.Troop(self.troopList[i].name + "+","soldier",1)
					else:
						self.troopList[i].xp += self.mission1.xp
						if self.troopList[i].xp >= (((self.troopList[i].level) * (self.troopList[i].level)) * 10) + 100:
							self.troopList[i].level += 1
							self.troopList[i].xp -= (((self.troopList[i].level) * (self.troopList[i].level)) * 10) + 100

    def generateReward(self):
    	reward = random.randint(Defines.RewardType.NONE, Defines.RewardType.WEAPON)
    	#if reward == RewardType.NONE:
    		#no reward
    	if reward == Defines.RewardType.money:
    		self.money += self.mission1.money * 2
    	elif reward == Defines.RewardType.XP:
    		self.mission1.xp += self.mission1.xp * 2
    	elif reward == Defines.RewardType.SCIENCE:
    		self.science += random.randint(50, 150) * self.mission1.difficulty
    	#elif reward == RewardType.ARMOUR:
    		#give armour
    	#elif reward == RewardType.WEAPON:
    		#give weapon

    def buildRooms(self):
    #output message saying available positions
    	for event in pygame.event.get(): # event handling loop
        	while event.type != KEYDOWN:
        		if event.type == QUIT:
        			Basecom.terminate()
        	if event.type == KEYDOWN:
        		if (event.key == K_UP):
        			y_Pos += 1
        		elif (event.key == K_DOWN):
        			y_Pos -= 1
        		elif (event.key == K_LEFT):
        			x_Pos -= 1
        		elif (event.key == K_RIGHT):
        			x_Pos += 1
        		if (event.key == K_ENTER):
        			self.Base.ChangeRoom(x_Pos, y_Pos)

    def game_render(self):
    	#render stuff
    	self.DISPLAYSURF.fill(BGCOLOR)
    	self.render_rooms()
        self.render_info()
        self.render_controls()
        self.render_troops()


    	for x in range(0, Defines.WINDOWWIDTH, Defines.CELLWIDTH): # draw vertical lines
    		pygame.draw.line(self.DISPLAYSURF, WHITE, (x, 206), (x, Defines.WINDOWHEIGHT))
    	for y in range(206, Defines.WINDOWHEIGHT, Defines.CELLHEIGHT): # draw horizontal lines
    		pygame.draw.line(self.DISPLAYSURF, WHITE, (0, y), (Defines.WINDOWWIDTH, y))

    	pygame.display.update()
    	self.FPSCLOCK.tick(Defines.FPS)

    def render_controls(self):
        stateSurf = self.BASICFONT.render('State: %i' %(self.state), True, WHITE)
        stateRect = stateSurf.get_rect()
        stateRect.topleft = (10, 100)
        self.DISPLAYSURF.blit(stateSurf, stateRect)

        buildConSurf = self.BASICFONT.render('Press B to Build Rooms', True, WHITE)
        buildConRect = buildConSurf.get_rect()
        buildConRect.topleft = (10, 120)
        self.DISPLAYSURF.blit(buildConSurf, buildConRect)

        missionConSurf = self.BASICFONT.render('Press Space to Select a Mission', True, WHITE)
        missionConRect = missionConSurf.get_rect()
        missionConRect.topleft = (10, 140)
        self.DISPLAYSURF.blit(missionConSurf, missionConRect)

    def render_info(self):
    	moneySurf = self.BASICFONT.render('Money: %s' % (self.base.money), True, WHITE)
    	moneyRect = moneySurf.get_rect()
    	moneyRect.topleft = (10, 10)
    	self.DISPLAYSURF.blit(moneySurf, moneyRect)

    	scienceSurf = self.BASICFONT.render('Science: %s' % (self.base.science), True, WHITE)
    	scienceRect = scienceSurf.get_rect()
    	scienceRect.topleft = (10, 30)
    	self.DISPLAYSURF.blit(scienceSurf, scienceRect)

    	powerSurf = self.BASICFONT.render('Power: %s' % (self.base.power), True, WHITE)
    	powerRect = powerSurf.get_rect()
    	powerRect = powerSurf.get_rect()
    	powerRect.topleft = (10, 50)
    	self.DISPLAYSURF.blit(powerSurf, powerRect)

    	troopSurf = self.BASICFONT.render('Troops: %s' % (len(self.troopList)), True, WHITE)
    	troopRect = troopSurf.get_rect()
    	troopRect.topleft = (10, 70)
    	self.DISPLAYSURF.blit(troopSurf, troopRect)

    def render_troops(self):
    	keySurf = self.BASICFONT.render(("Name        Type       Level      XP         Health     Armour     Damage     Accuracy     Evasion     Injured"), True, WHITE)
    	keyRect = keySurf.get_rect()
    	keyRect.topleft = (350, 10)
    	self.DISPLAYSURF.blit(keySurf, keyRect)

    	for x in range(0, len(self.troopList)):
			a = '%s' %self.troopList[x].name
			b = '%s' % self.troopList[x].troopType
			c = '%s' % self.troopList[x].level
			d = '%s' % self.troopList[x].health
			e = '/%s' % self.troopList[x].maxHealth
			f = '%s' % self.troopList[x].armour
			g = '%s' % self.troopList[x].damage
			h = '%s' % self.troopList[x].accuracy
			i = '%s' % self.troopList[x].evasion
			j = '%s' % self.troopList[x].xp
			k = '%s' % self.troopList[x].injured

			tnameSurf = self.BASICFONT.render((a), True, WHITE)
			tnameRect = tnameSurf.get_rect()
			tnameRect.topleft = (350, (((x+1)*15)+25))
			self.DISPLAYSURF.blit(tnameSurf, tnameRect)

			ttypeSurf = self.BASICFONT.render((b), True, WHITE)
			ttypeRect = ttypeSurf.get_rect()
			ttypeRect.topleft = (435, (((x+1)*15)+25))
			self.DISPLAYSURF.blit(ttypeSurf, ttypeRect)

			tlevelSurf = self.BASICFONT.render((c), True, WHITE)
			tlevelRect = tlevelSurf.get_rect()
			tlevelRect.topright = (555, (((x+1)*15)+25))
			self.DISPLAYSURF.blit(tlevelSurf, tlevelRect)

			txpSurf = self.BASICFONT.render((j), True, WHITE)
			txpRect = txpSurf.get_rect()
			txpRect.topright = (630, (((x+1)*15)+25))
			self.DISPLAYSURF.blit(txpSurf, txpRect)

			thealthSurf = self.BASICFONT.render((d+e), True, WHITE)
			thealthRect = thealthSurf.get_rect()
			thealthRect.topleft = (675, (((x+1)*15)+25))
			self.DISPLAYSURF.blit(thealthSurf, thealthRect)

			tarmourSurf = self.BASICFONT.render((f), True, WHITE)
			tarmourRect = tarmourSurf.get_rect()
			tarmourRect.topleft = (790, (((x+1)*15)+25))
			self.DISPLAYSURF.blit(tarmourSurf, tarmourRect)

			tdamageSurf = self.BASICFONT.render((g), True, WHITE)
			tdamageRect = tdamageSurf.get_rect()
			tdamageRect.topleft = (870, (((x+1)*15)+25))
			self.DISPLAYSURF.blit(tdamageSurf, tdamageRect)

			taccuraceySurf = self.BASICFONT.render((h), True, WHITE)
			taccuraceyRect = taccuraceySurf.get_rect()
			taccuraceyRect.topleft = (990, (((x+1)*15)+25))
			self.DISPLAYSURF.blit(taccuraceySurf, taccuraceyRect)

			tevasionSurf = self.BASICFONT.render((i), True, WHITE)
			tevasionRect = tevasionSurf.get_rect()
			tevasionRect.topleft = (1070, (((x+1)*15)+25))
			self.DISPLAYSURF.blit(tevasionSurf, tevasionRect)

			tijuredSurf = self.BASICFONT.render((k), True, WHITE)
			tijuredRect = tijuredSurf.get_rect()
			tijuredRect.topleft = (1170, (((x+1)*15)+25))
			self.DISPLAYSURF.blit(tijuredSurf, tijuredRect)

    def render_rooms(self):
		for i in range (0, Defines.FLOORNUM):
			for j in range (0, Defines.ROOMNUM):
				#draw_room = self.base.GetRoomType(i,j)
				if((self.base.GetRoomType(i,j)) == Defines.RoomType.EMPTY):
					roomRect = pygame.Rect((i*Defines.CELLWIDTH), (206+(j*Defines.CELLHEIGHT)), Defines.CELLWIDTH, Defines.CELLHEIGHT)
					self.DISPLAYSURF.blit(self.emptyRoomImage, roomRect)
				elif((self.base.GetRoomType(i,j)) == Defines.RoomType.SHAFT):
					   roomRect = pygame.Rect((i*Defines.CELLWIDTH), (206+(j*Defines.CELLHEIGHT)), Defines.CELLWIDTH, Defines.CELLHEIGHT)
					   self.DISPLAYSURF.blit(self.shaftRoomImage, roomRect)
				elif((self.base.GetRoomType(i,j))== Defines.RoomType.MONEY):
					roomRect = pygame.Rect((i*Defines.CELLWIDTH), (206+(j*Defines.CELLHEIGHT)), Defines.CELLWIDTH, Defines.CELLHEIGHT)
					self.DISPLAYSURF.blit(self.moneyRoomImage, roomRect)
				##                if((self.base.GetRoomType(i,j)) == Defines.RoomType.SCIENCE):
				##					roomRect = pygame.Rect((i*Defines.CELLWIDTH), (206+(j*Defines.CELLHEIGHT)), Defines.CELLWIDTH, Defines.CELLHEIGHT)
				##                	self.DISPLAYSURF.blit(self.scienceImageRoom, roomRect)
				elif((self.base.GetRoomType(i,j)) == Defines.RoomType.MED_BAYS):
					roomRect = pygame.Rect((i*Defines.CELLWIDTH), (206+(j*Defines.CELLHEIGHT)), Defines.CELLWIDTH, Defines.CELLHEIGHT)
					self.DISPLAYSURF.blit(self.med_bayRoomImage, roomRect)
				elif((self.base.GetRoomType(i,j)) == Defines.RoomType.POWER):
					roomRect = pygame.Rect((i*Defines.CELLWIDTH), (206+(j*Defines.CELLHEIGHT)), Defines.CELLWIDTH, Defines.CELLHEIGHT)
					self.DISPLAYSURF.blit(self.powerRoomImage, roomRect)
				elif((self.base.GetRoomType(i,j)) == Defines.RoomType.BARRACKS):
					roomRect = pygame.Rect((i*Defines.CELLWIDTH), (206+(j*Defines.CELLHEIGHT)), Defines.CELLWIDTH, Defines.CELLHEIGHT)
					self.DISPLAYSURF.blit(self.barracksRoomImage, roomRect)